package thread;
class MyBlockingQueue {
    private String[] elems = null;
    private int head = 0;
    private int tail = 0;
    private int size = 0;
    //准备一个锁对象
    private Object locker = new Object();
    public MyBlockingQueue(int capacity) {
        elems = new String[capacity];
    }
    public void put(String elem) throws InterruptedException {//里面基本上都是写操作所以要加锁
        synchronized (locker){
    while (size >= elems.length) {
        //队列满了
//        后续需要这个队列阻塞
        locker.wait();

        return;
    }
    //新的元素要放在tail指向的位置上去
        elems[tail] = elem;
        tail++;
    if(tail >= elems.length){
        tail = 0;
//        tail = tail % elems.length;//小于length就是tail原来的值
        //如果tail==length,求余的值就是0
    }
            size++;
    //入队列成功后进行唤醒
            locker.notify();
        }
    }
    public String take() throws InterruptedException {
        String elem = null;
        synchronized (locker) {
            while (size == 0) {//多一次确认
                locker.wait();
                //队列空了
                //后续也需要这个代码阻塞
                return null;
            }
            //去除head位置的元素并返回
            elem = elems[head];
            if (head >= elems.length) {
                head = 0;
            }
            head++;
            size--;
            //出队列完成之后,加上唤醒
            locker.notify();
            return elem;
        }
    }
}
public class ThreadDemo29 {
    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue queue = new MyBlockingQueue(1000);
//        queue.put("aaa");
//        queue.put("bbb");
//        queue.put("ccc");
//        queue.put("ddd");
//        String elem = "";
//        elem = queue.take();
//        System.out.println("elem: " + elem);
//        elem = queue.take();
//        System.out.println("elem: " + elem);
//        elem = queue.take();
//        System.out.println("elem: " + elem);
//        elem = queue.take();
//        System.out.println("elem: " + elem);
        //生产者
        Thread t1 = new Thread(() ->{
            int n = 1;
            while (true) {
                try {
                    queue.put(n + "");
                    System.out.println("生产元素: " + n);
                    n++;
//                    Thread.sleep(500);//生产的慢,消费的快
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        //消费者
        Thread t2 = new Thread(() ->{
            while (true) {
                try {
                    String n = queue.take();
                    System.out.println("消费元素 " + n);
                    Thread.sleep(500);//生产的快,消费的慢

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();

    }
}
